package com.ruoyi.eqmonitor.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.eqmonitor.domain.*;
import com.ruoyi.eqmonitor.service.ITzproblemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.hutool.http.HttpRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

/**
 * 台州路桥区河长制数据接口
 * @author ruoyi
 * @date 2023-05-23
 */
@Api(tags = "台州路桥区河长制数据接口")
@Slf4j
@RestController
@RequestMapping("/tzlqqapi")
public class TzLqqAPIController {

    public String appKey="4028979357ad44510157b1ac717c0025";
    public String appSecret="cae8b23ecb6c076a61f2e9f1573cb977";
    public String postUrl = "https://tz.ihezhang.com:8443/api/Hzt/";
    @Resource
    private ITzproblemService tzproblemService;

    @ApiOperation(value = "获取巡河问题记录")
    @GetMapping("/tzproblemlist")
    public JSONObject tzproblemList(TzProblemAPI tzProblemAPI){
        long timestamp = System.currentTimeMillis();
        String md5str = appKey+appSecret+timestamp;
        String token = DigestUtils.md5Hex(md5str);
        tzProblemAPI.setAppKey(appKey);
        tzProblemAPI.setTimestamp(String.valueOf(timestamp));
        String mm=HttpRequest.post(postUrl+"problemList")
                .header("Content-type", "application/x-www-form-urlencoded")
                .header("token",token)
                .form(JSON.parseObject(JSON.toJSONString(tzProblemAPI)))
                .execute()
                .body();
        JSONObject jsonObject=JSON.parseObject(mm);
        return jsonObject;
    }

    @ApiOperation(value = "获取全部巡河问题记录")
    @GetMapping("/tzproblemlistall")
    public JSONObject tzproblemListAll(TzProblemAPI tzProblemAPI){
        int totalCount=0;
        int limit=100;
        int page=1;
        long timestamp = System.currentTimeMillis();
        String md5str = appKey+appSecret+timestamp;
        String token = DigestUtils.md5Hex(md5str);
        tzProblemAPI.setAppKey(appKey);
        tzProblemAPI.setTimestamp(String.valueOf(timestamp));
        tzProblemAPI.setLimit((long)limit);
        tzProblemAPI.setPage((long)page);
        String mm=HttpRequest.post(postUrl+"problemList")
                .header("Content-type", "application/x-www-form-urlencoded")
                .header("token",token)
                .form(JSON.parseObject(JSON.toJSONString(tzProblemAPI)))
                .execute()
                .body();
        JSONObject jsonObject=JSON.parseObject(mm);
        totalCount = (int) jsonObject.get("totalCount");
        JSONArray jsonArray= jsonObject.getJSONArray("data");
        int sumPage = ((totalCount-1)/limit+1);
        for(int i=2;i<=sumPage;i++)
        {
            timestamp = System.currentTimeMillis();
            md5str = appKey+appSecret+timestamp;
            token = DigestUtils.md5Hex(md5str);
            tzProblemAPI.setAppKey(appKey);
            tzProblemAPI.setTimestamp(String.valueOf(timestamp));
            tzProblemAPI.setLimit((long)limit);
            tzProblemAPI.setPage((long)i);
            mm=HttpRequest.post(postUrl+"problemList")
                    .header("Content-type", "application/x-www-form-urlencoded")
                    .header("token",token)
                    .form(JSON.parseObject(JSON.toJSONString(tzProblemAPI)))
                    .execute()
                    .body();
            jsonObject=JSON.parseObject(mm);
            jsonArray.addAll(jsonObject.getJSONArray("data"));
        }

        TreeMap<String, Object> map = new TreeMap<>();
        map.put("totalCount",totalCount);
        map.put("data",jsonArray);
        JSONObject jsonObjectall = JSON.parseObject(JSON.toJSONString(map));
        return jsonObjectall;
    }

    @ApiOperation(value = "获取问题类别")
    @GetMapping("/tzproblemtype")
    public JSONObject tzproblemType(TzProblemTypeAPI tzProblemTypeAPI){
        long timestamp = System.currentTimeMillis();
        String md5str = appKey+appSecret+timestamp;
        String token = DigestUtils.md5Hex(md5str);
        tzProblemTypeAPI.setAppKey(appKey);
        tzProblemTypeAPI.setTimestamp(String.valueOf(timestamp));
        String mm=HttpRequest.post(postUrl+"problemType")
                .header("Content-type", "application/x-www-form-urlencoded")
                .header("token",token)
                .form(JSON.parseObject(JSON.toJSONString(tzProblemTypeAPI)))
                .execute()
                .body();
        JSONObject jsonObject=JSON.parseObject(mm);
        return jsonObject;
    }

    @ApiOperation(value = "获取河段数据")
    @GetMapping("/tzriverlist")
    public JSONObject tzriverList(TzRiverAPI tzRiverAPI){
        long timestamp = System.currentTimeMillis();
        String md5str = appKey+appSecret+timestamp;
        String token = DigestUtils.md5Hex(md5str);
        tzRiverAPI.setAppKey(appKey);
        tzRiverAPI.setTimestamp(String.valueOf(timestamp));
        String mm=HttpRequest.post(postUrl+"riverList")
                .header("Content-type", "application/x-www-form-urlencoded")
                .header("token",token)
                .form(JSON.parseObject(JSON.toJSONString(tzRiverAPI)))
                .execute()
                .body();
        JSONObject jsonObject=JSON.parseObject(mm);
        return jsonObject;
    }

    @ApiOperation(value = "获取问题处理过程")
    @GetMapping("/tzproblemhandlelist")
    public JSONObject tzproblemHandleList(TzProblemHandleAPI tzproblemHandleAPI){
        long timestamp = System.currentTimeMillis();
        String md5str = appKey+appSecret+timestamp;
        String token = DigestUtils.md5Hex(md5str);
        tzproblemHandleAPI.setAppKey(appKey);
        tzproblemHandleAPI.setTimestamp(String.valueOf(timestamp));
        String mm=HttpRequest.post(postUrl+"problemHandleList")
                .header("Content-type", "application/x-www-form-urlencoded")
                .header("token",token)
                .form(JSON.parseObject(JSON.toJSONString(tzproblemHandleAPI)))
                .execute()
                .body();
        JSONObject jsonObject=JSON.parseObject(mm);
        return jsonObject;
    }

    @ApiOperation(value = "获取公众问题记录")
    @GetMapping("/tzcomplainlist")
    public JSONObject tzcomplainList(TzComplainAPI tzComplainAPI){
        long timestamp = System.currentTimeMillis();
        String md5str = appKey+appSecret+timestamp;
        String token = DigestUtils.md5Hex(md5str);
        tzComplainAPI.setAppKey(appKey);
        tzComplainAPI.setTimestamp(String.valueOf(timestamp));
        String mm=HttpRequest.post(postUrl+"complainList")
                .header("Content-type", "application/x-www-form-urlencoded")
                .header("token",token)
                .form(JSON.parseObject(JSON.toJSONString(tzComplainAPI)))
                .execute()
                .body();
        JSONObject jsonObject=JSON.parseObject(mm);
        return jsonObject;
    }

    @ApiOperation(value = "获取全部公众问题记录")
    @GetMapping("/tzcomplainlistall")
    public JSONObject tzproblemListAll(TzComplainAPI tzComplainAPI){
        int totalCount=0;
        int limit=100;
        int page=1;
        long timestamp = System.currentTimeMillis();
        String md5str = appKey+appSecret+timestamp;
        String token = DigestUtils.md5Hex(md5str);
        tzComplainAPI.setAppKey(appKey);
        tzComplainAPI.setTimestamp(String.valueOf(timestamp));
        tzComplainAPI.setLimit((long)limit);
        tzComplainAPI.setPage((long)page);
        String mm=HttpRequest.post(postUrl+"complainList")
                .header("Content-type", "application/x-www-form-urlencoded")
                .header("token",token)
                .form(JSON.parseObject(JSON.toJSONString(tzComplainAPI)))
                .execute()
                .body();
        JSONObject jsonObject=JSON.parseObject(mm);
        totalCount = (int) jsonObject.get("totalCount");
        JSONArray jsonArray= jsonObject.getJSONArray("data");
        int sumPage = ((totalCount-1)/limit+1);
        for(int i=2;i<=sumPage;i++)
        {
            timestamp = System.currentTimeMillis();
            md5str = appKey+appSecret+timestamp;
            token = DigestUtils.md5Hex(md5str);
            tzComplainAPI.setAppKey(appKey);
            tzComplainAPI.setTimestamp(String.valueOf(timestamp));
            tzComplainAPI.setLimit((long)limit);
            tzComplainAPI.setPage((long)i);
            mm=HttpRequest.post(postUrl+"complainList")
                    .header("Content-type", "application/x-www-form-urlencoded")
                    .header("token",token)
                    .form(JSON.parseObject(JSON.toJSONString(tzComplainAPI)))
                    .execute()
                    .body();
            jsonObject=JSON.parseObject(mm);
            jsonArray.addAll(jsonObject.getJSONArray("data"));
        }

        TreeMap<String, Object> map = new TreeMap<>();
        map.put("totalCount",totalCount);
        map.put("data",jsonArray);
        JSONObject jsonObjectall = JSON.parseObject(JSON.toJSONString(map));
        return jsonObjectall;
    }

    @ApiOperation(value = "获取巡河率")
    @GetMapping("/tzpatrolrate")
    public JSONObject tzpatrolRate(TzPatrolRateAPI tzPatrolRateAPI){
        long timestamp = System.currentTimeMillis();
        String md5str = appKey+appSecret+timestamp;
        String token = DigestUtils.md5Hex(md5str);
        tzPatrolRateAPI.setAppKey(appKey);
        tzPatrolRateAPI.setTimestamp(String.valueOf(timestamp));
        String mm=HttpRequest.post(postUrl+"patrolRate")
                .header("Content-type", "application/x-www-form-urlencoded")
                .header("token",token)
                .form(JSON.parseObject(JSON.toJSONString(tzPatrolRateAPI)))
                .execute()
                .body();
        JSONObject jsonObject=JSON.parseObject(mm);
        return jsonObject;
    }

    @ApiOperation(value = "获取河湖长履职积分")
    @GetMapping("/tzworkscore")
    public JSONObject tzworkScore(TzWorkScoreAPI tzWorkScoreAPI){
        long timestamp = System.currentTimeMillis();
        String md5str = appKey+appSecret+timestamp;
        String token = DigestUtils.md5Hex(md5str);
        tzWorkScoreAPI.setAppKey(appKey);
        tzWorkScoreAPI.setTimestamp(String.valueOf(timestamp));
        String mm=HttpRequest.post(postUrl+"workScore")
                .header("Content-type", "application/x-www-form-urlencoded")
                .header("token",token)
                .form(JSON.parseObject(JSON.toJSONString(tzWorkScoreAPI)))
                .execute()
                .body();
        JSONObject jsonObject=JSON.parseObject(mm);
        return jsonObject;
    }

    /**
     * 导出巡河问题记录
     */
    @Log(title = "巡河问题记录导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export1")
    public void export(HttpServletResponse response,TzProblemAPI tzProblemAPI){
        JSONObject jsonObject = this.tzproblemList(tzProblemAPI);
        JSONArray jsonArray= jsonObject.getJSONArray("data");
        List<TzProblem> list = JSONArray.parseArray(jsonArray.toJSONString(), TzProblem.class);
        ExcelUtil<TzProblem> util = new ExcelUtil<TzProblem>(TzProblem.class);
        util.exportExcel(response, list, "巡河问题数据");
    }

    /**
     * 导出河段信息
     */
    @Log(title = "河段信息导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export2")
    public void export2(HttpServletResponse response,TzRiverAPI tzRiverAPI){
        JSONObject jsonObject = this.tzriverList(tzRiverAPI);
        JSONArray jsonArray= jsonObject.getJSONArray("data");
        List<TzRiver> list = JSONArray.parseArray(jsonArray.toJSONString(), TzRiver.class);
        ExcelUtil<TzRiver> util = new ExcelUtil<TzRiver>(TzRiver.class);
        util.exportExcel(response, list, "河段信息数据");
    }

    /**
     * 每2小时执行一次,获取当月数据
     * 台州的功能  嵊州暂时去掉了
     */
    /*@Scheduled(cron = "0 0 0/2 * * ?")
    @Profile("prod")
    public void problemTask() {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String startDay = df.format(new Date());
            Calendar calendar = Calendar.getInstance();
            calendar.set(Integer.parseInt(startDay.substring(0,4)), Integer.parseInt(startDay.substring(5,7)) - 1, 1);
            String firstDayOfMonth = new SimpleDateFormat( "yyyy-MM-dd").format(calendar.getTime());
            calendar.set(Integer.parseInt(startDay.substring(0,4)), Integer.parseInt(startDay.substring(5,7)), 1);
            calendar.add(Calendar.DATE, -1);
            String lastDayOfMonth = new SimpleDateFormat( "yyyy-MM-dd").format(calendar.getTime());
            TzProblemAPI tzProblemAPI = new TzProblemAPI();
            tzProblemAPI.setStartTime(firstDayOfMonth+" 00:00:00");
            tzProblemAPI.setEndTime(lastDayOfMonth+" 23:59:59");
            JSONObject jsonObject = this.tzproblemListAll(tzProblemAPI);
            JSONArray jsonArray= jsonObject.getJSONArray("data");
            List<TzProblem> list = JSONArray.parseArray(jsonArray.toJSONString(), TzProblem.class);
            boolean z = tzproblemService.saveBatch(list);
            if(z){
                Calendar myTime = Calendar.getInstance();
                myTime.add(Calendar.MINUTE,-30);
                Date beforeM = myTime.getTime();
                String beforeM60 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(beforeM);
                LambdaQueryWrapper<TzProblem> wrapper = Wrappers.lambdaQuery();
                wrapper.lt(TzProblem::getCreateTime,beforeM60);
                tzproblemService.remove(wrapper);
            }
        } catch (Exception e) {
            log.error("日累计定时任务执行失败", e);
        }
    }*/
}
